<script setup lang="ts">
import { ref, onMounted } from "vue"
import { ElMessage } from "element-plus"

import { petTypeList, petBreedList, searchPetById } from "@/api/pets"
import type { Pet, PetType, PetBreed } from "@/api/pets"

const props = defineProps<{
    petId: number,
    onBack: () => void
}>()

const pet = ref<Pet | null>(null)
const typeList = ref<PetType[]>([])
const breedList = ref<PetBreed[]>([])
const loading = ref(false)

/* 上传头像请求地址 */
// ❗ 按你的项目结构自动区分环境
const uploadUrl = import.meta.env.MODE === "development"
    ? "/api/api/upload/pet/avatar"
    : "/api/upload/pet/avatar"

/* 获取宠物详情 */
const loadPet = async () => {
    loading.value = true
    const res = await searchPetById(props.petId)
    pet.value = res.data
    loading.value = false
}

const loadTypes = async () => {
    const res = await petTypeList()
    typeList.value = res.data
}

const loadBreeds = async (typeId: number) => {
    const res = await petBreedList({ petTypeId: typeId })
    breedList.value = res.data
}

const handlePetTypeChange = async (typeId: number) => {
    await loadBreeds(typeId)
    pet.value!.breed = breedList.value[0]?.id ?? 0
}

/* 头像上传前校验 */
const beforeAvatarUpload = (file: File) => {
    const isValid = ["image/jpeg", "image/png"].includes(file.type)
    if (!isValid) {
        ElMessage.error("头像必须为 JPG 或 PNG 格式！")
        return false
    }
    if (file.size / 1024 / 1024 > 2) {
        ElMessage.error("头像大小不能超过 2MB！")
        return false
    }
    return true
}

/* 上传成功 */
const handleAvatarSuccess = (res: any) => {
    pet.value!.avatar = res.data.url
    ElMessage.success("头像更新成功！")
}

/* 保存 */
const savePet = async () => {
    ElMessage.success("（你的保存接口未启用）已模拟保存成功")
    props.onBack()
}

onMounted(async () => {
    await loadTypes()
    await loadPet()
    await loadBreeds(pet.value!.type)
})
</script>

<template>
    <div class="detail-page" v-loading="loading">

        <el-button type="primary" class="back-btn" @click="props.onBack">← 返回</el-button>

        <div class="detail-info">
            <el-card class="detail-card" v-if="pet">

                <h2 class="title">宠物详情</h2>

                <el-form label-width="90px" class="detail-form">

                    <!-- 头像上传 -->
                    <el-form-item label="头像">
                        <div class="avatar-wrapper">
                            <img :src="pet.avatar" class="avatar" />
                            <el-upload :action="uploadUrl" :show-file-list="false" :before-upload="beforeAvatarUpload"
                                :on-success="handleAvatarSuccess" class="change-avatar-btn">
                                <el-button size="small" type="primary">更换头像</el-button>
                            </el-upload>
                        </div>
                    </el-form-item>

                    <el-form-item label="名字">
                        <el-input v-model="pet.name" clearable />
                    </el-form-item>

                    <el-form-item label="类型">
                        <el-select v-model="pet.type" @change="handlePetTypeChange">
                            <el-option v-for="t in typeList" :key="t.id" :label="t.name" :value="t.id" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="品种">
                        <el-select v-model="pet.breed">
                            <el-option v-for="b in breedList" :key="b.id" :label="b.name" :value="b.id" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="性别">
                        <el-select v-model="pet.gender">
                            <el-option label="公" :value="1" />
                            <el-option label="母" :value="2" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="生日">
                        <el-date-picker v-model="pet.birthday" value-format="YYYY-MM-DD" />
                    </el-form-item>

                    <el-form-item label="领养日期">
                        <el-date-picker v-model="pet.adoption_date" value-format="YYYY-MM-DD" clearable />
                    </el-form-item>

                    <el-form-item label="描述">
                        <el-input type="textarea" v-model="pet.remark" rows="3" resize="none" />
                    </el-form-item>
                </el-form>

                <div class="footer-btns">
                    <el-button @click="props.onBack">取消</el-button>
                    <el-button type="primary" @click="savePet">保存</el-button>
                </div>
            </el-card>
        </div>
    </div>
</template>

<style scoped>
.detail-page {
    height: 100%;
}

.detail-info {
    height: 100%;
}

.back-btn {
    margin-bottom: 10px;
}

.detail-card {
    max-width: 520px;
    height: 100%;
    margin: 0 auto;
    padding: 0px 0px;
    border-radius: 16px;
    background: #fff;
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.06);
}

.title {
    text-align: center;
    font-size: 22px;
    font-weight: 700;
    margin-bottom: 20px;
}

.detail-form .el-form-item {
    margin-bottom: 18px;
}

.avatar-wrapper {
    display: flex;
    align-items: center;
    gap: 15px;
}

.avatar {
    width: 120px;
    height: 120px;
    border-radius: 12px;
    object-fit: cover;
    box-shadow: 0 2px 12px rgba(0, 0, 0, .12);
    transition: transform .25s;
}

.avatar:hover {
    transform: scale(1.03);
}

.change-avatar-btn {
    margin-top: 5px;
}

.footer-btns {
    text-align: right;
    margin-top: 20px;
}
</style>
